package com.pyip.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.pyip.reggie.common.BaseContext;
import com.pyip.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI(); // 获取本次的url地址
        log.info("拦截请求"+requestURI);
        // 不需要处理的请求路径
        String[] urls = new String[]{
          "/employee/login",
          "/employee/logout",
          "/backend/**",
          "/front/**",
          "/common/**", // 文件下载上传功能
           "/user/login",//用户登陆
           "/user/sendMsg",  // 发送验证码
                "/doc.html",  // swagger2相关
                "/webjars/**", // swagger2相关
                "/swagger-resources", // swagger2相关
                "/v2/api-docs" // swagger2相关
        };
        Boolean flag = check(urls,requestURI);
        // 判断是否需要过滤
        if(flag){
            log.info("不需要处理的请求"+requestURI);
            filterChain.doFilter(request,response);
            return;
        }
//        员工登陆了
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已登陆,用户id为"+request.getSession().getAttribute("employee"));
            // 用于公共字段填充
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);

            filterChain.doFilter(request,response);
            return;
        }
//        用户登陆了
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登陆,用户id为"+request.getSession().getAttribute("user"));
            // 用于公共字段填充
            Long id = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(id);

            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登陆");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
